package org.ecype.diego.demo;

import static org.ecype.util.Assert.aassert;

import org.ecype.diego.AbstractUriProcessor;
import org.ecype.diego.Uris;
import org.ecype.diego.demo.DemoContract.Question;
import org.ecype.diego.demo.DemoContract.QuestionState;
import org.ecype.util.Nulls;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import androidx.persistence.Id;

public class PendingQuestionProcessor extends AbstractUriProcessor {

	private static final String SELECTION = Question.STATE + " = " + QuestionState.PENDING;
	private static final String[] ID_PROJECTION = new String[] { Id.COLUMN_NAME };

	private static final int DEFAULT_TOPIC = 1;

	private final ContentValues values;

	public PendingQuestionProcessor() {
		values = new ContentValues();
		values.put(Question.TOPIC, DEFAULT_TOPIC);
		values.put(Question.STATE, QuestionState.PENDING);
	}

	@Override
	public Cursor query(Uri uri, Uri notifyUri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		Nulls.checkAreAreNull(selection, selectionArgs, sortOrder);
		Cursor pending = innerQuery(projection);
		if (!pending.moveToFirst()) {
			values.put(Question.DATE, System.currentTimeMillis());
			provider.insert(Question.URI, values);
			return query(uri, notifyUri, projection, null, null, null);
		} else {
			return pending;
		}

	}

	@Override
	public int update(Uri uri, Uri notifyUri, ContentValues values, String selection, String[] selectionArgs) {
		Nulls.checkAreAreNull(selection, selectionArgs);
		Cursor pending = provider.query(uri, ID_PROJECTION, null, null, null);
		aassert(pending.moveToFirst());
		long id = pending.getLong(0);
		pending.close();
		return provider.update(Uris.withAppendedId(Question.URI, id), notifyUri, values, null, null);
	}

	private Cursor innerQuery(String[] projection) {
		return provider.query(Question.URI, projection, SELECTION, null, null);
	}

	@Override
	public String getType(Uri uri) {
		return URI_ITEM + "question";
	}
}
